package cn.vihub.controller;

import cn.vihub.param.ShopMenuParam;
import cn.vihub.pojo.ShopMenu;
import cn.vihub.service.ShopMenuService;
import cn.vihub.utils.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("shop-user/menu")
public class MenuController {

    @Autowired
    private ShopMenuService shopMenuService;

    @GetMapping("tree")
    public Result<Object> tree(){
        return Result.success(shopMenuService.getTree());
    }

    /**
     * 菜单添加编辑
     * @param
     * @return
     */
    @PostMapping("save")
    public Result<Boolean> save(@RequestBody ShopMenuParam shopMenuParam){

        ShopMenu shopMenu = new ShopMenu();
        BeanUtils.copyProperties(shopMenuParam, shopMenu);

        return shopMenuService.saveOrUpdate(shopMenu)?Result.success():Result.error();
    }

    /**
     * 菜单删除
     * @param id
     * @return
     */
    @DeleteMapping("delete/{id}")
    public Result<Boolean> delete(@PathVariable("id") Integer id){

        //验证当前菜单下是否存在子菜单
        shopMenuService.isMenuByPid(id);

        if (shopMenuService.removeById(id)){
            return Result.success();
        }else {
            return Result.error();
        }

    }

    /**
     * 通过用户id获取用户所拥有的菜单树
     * @param userId
     * @return
     */
    @GetMapping("treeByUserId/{userId}")
    public Result<Object> treeByUserId(@PathVariable("userId") Integer userId){
        return Result.success(shopMenuService.treeByUserId(userId));
    }

    /**
     * 通过角色id查询角色所拥有得菜单列表（不是树）
     */
    @GetMapping("listByRoleId/{roleId}")
    public Result<List<ShopMenu>> listByRoleId(@PathVariable("roleId") Integer roleId){
        return Result.success(shopMenuService.listByRoleId(roleId));
    }

}
